﻿using Gameserver.DAO;
using ServerFrame;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Gameserver.Cache
{
    public class RoleCache
    {
        public int Role_id = 0;//缓存中的ID，与角色ID无关
        public Dictionary<int, string> RidToName = new Dictionary<int, string>();//根据缓存id获取角色信息，用于判断该账户是否有角色
        public Dictionary<string, Role_DAO> RnameToRole = new Dictionary<string, Role_DAO>();//根据name绑定角色，用于判断该账户是否有角色
        public Dictionary<string, Mytoken> Online_Role = new Dictionary<string, Mytoken>();
        public Dictionary<Mytoken, Role_DAO> Online_token = new Dictionary<Mytoken, Role_DAO>();
        /// <summary>
        /// 根据角色ID判断是否存在角色
        /// </summary>
        /// <param name="rid"></param>
        /// <returns></returns>
        public bool hasRole(int rid)
        {
            if(rid==-1)
            { return false; }
            if (RidToName.ContainsKey(rid))
                return true;
            return false;
        }
        public bool hasRole(string Rname)
        {
            if (RnameToRole.ContainsKey(Rname))
                return true;
            return false;
        }
        public void Create(User_DAO user,string name)
        {
            System.Threading.Interlocked.Increment(ref Role_id);
            Role_DAO role = new Role_DAO(Role_id, name);
            RidToName.Add(role.role_id, role.rolename);
            RnameToRole.Add(role.rolename, role);
        }
        public bool isOnline(string name)
        {
            return Online_Role.ContainsKey(name);
        }
        public void Online(string name,Mytoken token)
        {
            Online_Role.Add(name, token);
            Online_token.Add(token, RnameToRole[name]);
        }
        public void Offline(string name,Mytoken token)
        {
            Online_Role.Remove(name);
            Online_token.Remove(token);
        }
        public void SaveRole(int rid,string name,Role_DAO role)
        {
            //保存角色消息
            RnameToRole[name] = role;
            RidToName[rid] = role.rolename;
        }
        public Role_DAO GetRoleByToken(Mytoken token)
        {
            if(!Online_token.ContainsKey(token))
            {
                return null;
            }
            return Online_token[token];
        }
        public string GetNameByToken(Mytoken token)
        {
            if (!Online_token.ContainsKey(token))
            {
                return null;
            }
            return Online_token[token].rolename;
        }
        public Mytoken GetTokenByName(string name)
        {
            if(!Online_Role.ContainsKey(name))
            {
                return null;
            }
            return Online_Role[name];
        }
    }
}
